package com.yonyou.train.service;

import com.alibaba.fastjson.JSONObject;
import com.yonyou.train.algorithem.PBKDF2;
import com.yonyou.train.exception.LoginException;
import com.yonyou.train.exception.LoginOutException;
import com.yonyou.train.exception.UpdatePwdException;
import com.yonyou.train.util.index.IndexUtil;
import com.yonyou.train.yonyouec.SyncEcUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.yonyou.train.dao.UserDao;
import com.yonyou.train.model.User;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * Created by zggdczfr on 2017/1/23.
 */
@Service
public class UserService {
    private static final Logger LOG = LoggerFactory.getLogger(SyncEcUser.class);

    @Autowired
    private UserDao userMapper;


    public int add(User user) {
        return userMapper.insertUser(user);
    }

    public User findById(long id) {
        return userMapper.findById(id);
    }

    public User findByName(String name) {
        return userMapper.findByName(name);
    }

    /**
     * 处理登录业务
     *
     * @param mobile
     * @param pwd
     * @param request
     * @return
     */
    public String login(String mobile, String pwd, HttpServletRequest request) {
        User user = userMapper.findByMobile(mobile);
        if (user == null) {
            throw new LoginException("用户名错误");
        }
        ;
        if (!PBKDF2.authenticate(pwd, user.getPassword().substring(0, PBKDF2.HASH_BIT_SIZE / 4), user.getPassword().substring(PBKDF2.HASH_BIT_SIZE / 4))) {
            throw new LoginException("密码错误");
        }
        //验证当前浏览器是否有其他用户已登录
        if (request.getSession().getAttribute("yh") != null) {
            //如果是自己

            return user.getMobile();
        } else {
            //如果不是自己

            request.getSession().setAttribute("yh", user);
            return user.getMobile();
        }
    }

    /**
     * 处理登出业务
     *
     * @param session_mobile
     * @param request
     */
    public void loginout(String session_mobile, HttpServletRequest request) {
        HttpSession session = request.getSession();
        if (session.getAttribute("yh") != null) {
            User user = (User) session.getAttribute("yh");
            session.invalidate();

        } else {

            throw new LoginOutException("退出失败！");
        }
    }

    /**
     * 修改密码业务
     *
     * @param mobile
     * @param oldpwd
     * @param newpwd
     */
    public void updatepwd(String mobile, String oldpwd, String newpwd) {
        //查询现在密码（包含盐）
        String oraginpwd = userMapper.findPwdByMobile(mobile);
        //如果用户不存在
        if (oraginpwd == null) {
            throw new UpdatePwdException("用户不存在");
        } else {
            String nowpwd = oraginpwd.substring(0, PBKDF2.HASH_BIT_SIZE / 4);
            String encodeoldpwd = PBKDF2.getEncryptedPassword(oldpwd, oraginpwd.substring(PBKDF2.HASH_BIT_SIZE / 4));
            if (!nowpwd.equals(encodeoldpwd)) { //密码不正确
                throw new UpdatePwdException("密码不正确");
            } else if (oldpwd.equals(newpwd)) {//密码重复
                throw new UpdatePwdException("密码重复");
            } else {
                if (!userMapper.updatepwd(mobile, PBKDF2.getPwd(newpwd))) {
                    throw new UpdatePwdException("更新密码失败");
                }
            }
        }


    }

    /*同步*/
    public void synchronizeUser() {

        //获取友空间的全部数据，并且放到新集合里面
        SyncEcUser syncEcUser = SyncEcUser.getInstance();
        ArrayList<JSONObject> usersA = new ArrayList<>();
        usersA = syncEcUser.doGetUser();

        //得到集合的数据，绑定到用户对象里面；然后将对象传递到业务层；
        int a = usersA.size();
        long id = 0;
        int aa = 0;
        User user = new User();
        for (aa = 0; aa < usersA.size(); aa++) {
            id = Integer.parseInt(usersA.get(aa).getString("id"));
            LOG.info("userservice获取到用户信息id：" + id);

//            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            Date date=new Date();
            //对用户进行同步；
            LOG.info("userservice获取用户信息：插入前：" + userMapper.findById(id));
            if (userMapper.findById(id) == null) {
                user.setName(usersA.get(aa).getString("name"));
                user.setId(id);
                user.setEmail(usersA.get(aa).getString("email"));
                user.setSex(usersA.get(aa).getString("sex"));
                user.setDept_id(usersA.get(aa).getLong("dept_id"));
                user.setDept_name(usersA.get(aa).getString("dept_name"));
                user.setMobile(usersA.get(aa).getString("mobile"));
                user.setStaff_no(usersA.get(aa).getString("staff_no"));
                user.setAvatar(usersA.get(aa).getString("avatar"));
//                String s=usersA.get(aa).getString("join_date");
//
//                try {
//                   date= sdf.parse(s);
//                } catch (ParseException e) {
//                    e.printStackTrace();
//                }
//                user.setJoin_date(date);

                userMapper.insertUserOne(user);
            } else {
                user.setName(usersA.get(aa).getString("name"));
                user.setId(id);
                user.setEmail(usersA.get(aa).getString("email"));
                user.setSex(usersA.get(aa).getString("sex"));
                user.setDept_id(usersA.get(aa).getLong("dept_id"));
                user.setDept_name(usersA.get(aa).getString("dept_name"));
                user.setMobile(usersA.get(aa).getString("mobile"));
                user.setStaff_no(usersA.get(aa).getString("staff_no"));
                user.setAvatar(usersA.get(aa).getString("avatar"));
//                String s=usersA.get(aa).getString("join_date");
//
//                try {
//                    date= sdf.parse(s);
//                } catch (ParseException e) {
//                    e.printStackTrace();
//                }
//                user.setJoin_date(date);
                userMapper.updateUser(user);
            }
            LOG.info("userservice获取到用户信息：插入后：" + userMapper.findById(id));
        }
    }
    public User getUserbyCode(String code){
        SyncEcUser ecUser = SyncEcUser.getInstance();
        JSONObject userJson = ecUser.getUserByCode(code);//
        String id = "";
        if (null != userJson){
            id = userJson.getString("member_id");
        }else {
            id = "2890424";
        }
        User user = findById(Long.valueOf(id).longValue());
        return user;
    }

    public void updateIndex() {
        //查询所有人员名单
        List<String> names = userMapper.GetAllUserNames();
        IndexUtil.createIndex(names);
    }
}
